//宫格
import uniGrid from "/uni_modules/uni-grid/components/uni-grid/uni-grid.vue";
// 公共头部
import myHeader from "/pages/headerfoot/pages/header.vue";
//cache缓存
import Cache from '@/utils/cache.js';
//打帮赛方法
import hitmatchcommon from '@/common/hitmatchcommon.js';
//基础
import Base from '@/common/base.js'
import base from "@/common/base.js";

export default {
	props: {
		code: String,
		project_make_id: String,
		project_id: String,
		gametype: String,
		initiator: String
	},
	components: {
		myHeader,
		uniGrid
	},
	data() {
		return {
			grade: 1, //等级
			num: 0, //默认层数
			numberarr: [], //出题
			show: true, //是否显示
			type: '', //类型 sz=数字 zm=字母 7jue=7言绝句 7lv=7言律诗
			times: '0', //分钟
			seconds: '0', //秒
			baseScore: 0, //基础分数
			fractionsPerSecond: 0, //每秒分数
			letters: ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "m", "n", "o", "p", "q", "r", "s", "t",
				"u", "v", "w", "x", "y", "z"
			], //字母
			number: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27,
				28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
				53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77,
				78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100
			],
			question: [], //出题
			defaultdigit: 0, //点击
			originalData: [], //原始数据
			answertime: 0, //答题用时
			typearr: {
				'sz': '数字',
				'zm': '字母',
				'7jue': '7言绝句',
				'7lv': '7言律诗'
			}, //类型 sz=数字 zm=字母 7jue=7言绝句 7lv=7言律诗
			level_dat: [], // 得分条件
			nowfrequency: 1, //当前次数
			proportion: 0, //比例
			btn: [],
			btna: ['继续下一题', '返回关卡列表', '返回项目选择', '查看排行榜', '再次打榜','提交分数'],
			btnb: ['立即进入下一关', '返回关卡列表', '返回项目选择', '查看排行榜', '再次打榜','提交分数'],
			btnc: ['', '返回关卡列表', '返回项目选择', '查看排行榜', '再次打榜','提交分数'],
			ifpass: false, //闯关结果弹出
			passTheResult: ['闯关成功', '闯关失败'],
			passtitle: '',
			fraction: 0, //分数
			thisLevelfraction: 0, //本关分数
			thisLeveltime: 0, //本关用时
			ifgame: true, //是否点击列表开始游戏
			censorship: [], //已经测试关卡
			selectedindex: 99, //选中特效数字 99没有数字
			successnumberarr: [], //正确数组
			my_answer: [], //我的答案
			originalseconds: 0, //原始数据
			coding:'',//编码
		}
	},
	mounted  (option = '') {
		var that = this;
		console.log(that.gametype);//对战类型
		console.log(that.initiator);//发起人
		
		//console.log(that.code);//编码
		if(that.code){
			that.coding=that.code;
		}
		//console.log(that.project_make_id);//赛事
		if(that.project_make_id){
			Cache.set('project_make_id',that.project_make_id)
		}
		//console.log(that.project_id);//项目
		if(that.project_id){
			Cache.set('project_id',that.project_id)
		}
		//判断项目ID
		that.ifprojectmakeid();
		//得到项目配置ID
		that.getMakeProjecParameter();
	},


	onLoad(option = '') {
		console.log(option);
	},
	methods: {
		//判断
		ifprojectmakeid() {
			if (!Cache.get('project_make_id') || Cache.get('project_make_id').length <= 0) {
				Base.publicshowtoasterror("请选择赛事", hitmatchcommon.automaticurl('gamelist'));
			}
			if (!Cache.get('project_id') || Cache.get('project_id').length <= 0) {
				Base.publicshowtoasterror("请选择项目", hitmatchcommon.automaticurl('matcheslist') + "?id=" + Cache.get(
					'project_make_id'));
			}
		},
		//得到项目配置
		async getMakeProjecParameter() {
			var that = this;
			var data = {};
			data['project_id'] = Cache.get('project_id');
			data['make_user_id'] = Cache.get('user_id');
			data['make_id'] = Cache.get('project_make_id');
			hitmatchcommon.getMakeProjecParameterLibMethod(data).then(res => {
				if (res) {
					that.level_dat = res.make_project_parameter_list; //等级列表
					that.censorship = res.make_project_user_achievement; //已过关
				}
			});
		},

		//默认题
		async defaultQuestion() {
			var that = this;
			//是否最后题
			that.ifend();
			//判断是否下一关
			that.judgeTheNextLevel();
			//次数判断

			var leveldata = that.level_dat[that.grade]; //获取等级
			var numberOfTests = leveldata['numberOfTests']; //获取测试次数
			that.num = leveldata['num']; //层数
			that.type = leveldata['type']; //类型
			that.proportion = parseFloat(100 / that.num - 1); //比例
			that.times = '0'; //分钟

			that.seconds = leveldata['min_time']; //秒
			that.originalseconds = leveldata['min_time']; //原始秒
			if (leveldata['min_time'] <= 9) {
				that.seconds = '0' + leveldata['min_time']; //秒
			}

			that.baseScore = leveldata['min_time_score']; //基础分数
			that.fractionsPerSecond = leveldata['one_seconds_score']; //每秒分数

			that.nowfrequency++; //当前次数

			await that.getoriginalData(); //获取原始数据
			await that.getnumber(); //获取数组

			that.show = true; //是显示	
		},
		//点击特效
		clickEffects(number) {
			var that = this;
			that.selectedindex = number
			setTimeout(function() {
				that.selectedindex = 99; //选中特效数字 99没有数字
			}, 200); // 这里的 1000 表示延时的时间，单位是毫秒
		},
		//次数判断
		orderJudgment() {
			var that = this;
			var number = that.level_dat[that.grade]['numberOfTests']; //获取测试次数
			if (that.nowfrequency > number) {
				that.btn = that.btnb; //下一关
			} else {
				that.btn = that.btna; //下一题
			}
		},
		//跳转
		clickList(e) {
			var that = this;
			if (e == '0') {
				that.defaultQuestion(); //创建题目 
				that.ifpass = false; //闯关结果弹出
			}
			//返回关卡列表
			if (e == '1') {
				//得到项目配置ID
				that.getMakeProjecParameter();
				that.ifgame = true; //返回列表
				that.ifpass = false; //否显示	
			}
			//返回项目选择
			if (e == '2') {
				uni.reLaunch({
					url: hitmatchcommon.automaticurl('matcheslist') + "?id=" + Cache.get('project_make_id'),
				})
			}
			//排行榜
			if (e == '3') {
				uni.reLaunch({
					url: hitmatchcommon.automaticurl('ranking') + "?id=" + Cache.get('project_make_id'),
				})
			}
			//再次打榜
			if (e == '4') {
				that.hitTheListAgain(); //再次打榜
			}
			//提交分数
			if (e == '5') {
				//提交分数 0=未提交 1=提交
				that.submit(that.answertime, that.fraction, that.grade, 0,1);
				Base.publicshowtoastsuccess('提交成功',hitmatchcommon.automaticurl('matcheslist') + "?id=" + Cache.get('project_make_id'));
			}
		},
		//再次打榜
		hitTheListAgain() {
			var that = this;
			that.ifpass = false; //否显示	
			that.nowfrequency = 1; //当前次数重置
			that.thisLevelfraction = 0; //本关分数
			that.thisLeveltime = 0; //本关用时
			that.defaultQuestion(); //创建题目 
		},
		//判断是否下一关
		judgeTheNextLevel() {
			var that = this;
			var number = that.level_dat[that.grade]['numberOfTests']; //获取测试次数
			if (that.nowfrequency > number) {
				that.grade++;
				that.nowfrequency = 1; //当前次数重置
				that.thisLevelfraction = 0; //本关分数
				that.thisLeveltime = 0; //本关用时
			}
		},
		//是否最后题
		ifend() {
			var that = this;
			var number = that.level_dat[that.grade]['numberOfTests']; //获取测试次数
			if (that.grade == 12 && that.nowfrequency > number) {
				console.log('最后题');
				return;
			}
		},
		//开始游戏
		selectgame(e) {
			var that = this;
			if (that.ifdown(e)) {
				that.grade = e; //选择等级
				that.ifgame = false; //是否点击列表开始游戏
				that.defaultQuestion(); //默认题
				if(!that.coding){
					that.coding=new Date().getTime();//设置编码
				}
			} else {
				Base.publicshowtoasterror('请解锁上关卡');
			}
		},

		//判断是否下一关
		ifdown(index = '') {
			var that = this;
			if (that.level_dat[index].isopen == 1 || that.level_dat[index].isopen == 2) {
				return true;
			} else {
				return false;
			}
		},
		//闯关结果
		passTheResults(pass = 0) {
			var that = this;
			that.selectedindex = 99; //选中特效数字 99没有数字
			that.passtitle = that.passTheResult[pass]; //闯关标题

			// that.fraction = (that.baseScore + ((parseInt(that.seconds) - (that.answertime)) * that.fractionsPerSecond)).toFixed(4); //分数
			that.fraction = (that.baseScore + ((parseInt(that.originalseconds) - parseInt(that.answertime)) * that
				.fractionsPerSecond)); //分数
			if (pass == '1') {
				that.fraction = 0; //错误分数为0
				//再次打榜
				that.btn = that.btnc; //再次打榜
			} else {
				that.orderJudgment();
			}

			that.thisLevelfraction = (parseFloat(that.thisLevelfraction) + parseFloat(that.fraction)); //本关分数

			that.thisLeveltime = that.thisLeveltime + that.answertime; //本关用时

			//提交答案
			that.submit(that.answertime, that.fraction, that.grade, pass);

			that.ifpass = true; //闯关结果弹出
		},
		//提交答案  clearance  0 过关 1=不过关
		submit(answertime = 0, allscore = 0, level = 0, clearance = 0,project_user_achievement_end=0) {
			var that = this;
			var data = {};
			if (clearance == '0') {
				clearance = 1;
			} else {
				clearance = 0;
			}
			data['project_id'] = Cache.get('project_id');
			data['make_user_id'] = Cache.get('user_id');
			data['make_id'] = Cache.get('project_make_id');
			data['questions_answer'] = that.successnumberarr; //问题
			data['my_answer'] = that.my_answer; //我的答案
			data['answertime'] = answertime; //答题用时
			data['allscore'] = allscore; //我的分数
			data['level'] = level; //关卡
		
			data['clearance'] = clearance; //是否过关
			data['make_project_user_code'] = that.coding; //编码
			data['project_user_achievement_end'] = project_user_achievement_end; //提交分数 0=未提交 1=提交
			data['topic'] = that.nowfrequency; //题数

			hitmatchcommon.setProjectUserAchievementLibMethod(data); //提交分数
		},
		//开始
		begin() {
			var that = this;
			//打乱数组
			that.numberarr = that.shuffle(that.question);
			that.answertime = 0; //答题用时
			that.defaultdigit = 0;
			that.fraction = 0; //分数
			that.countdown(); //倒计时
			that.show = false; //否显示	
		},
		//倒计时
		countdown() {
			var that = this;
			var times = parseInt(that.times); //分钟
			var seconds = parseInt(that.seconds); //秒
			that.timer = setInterval(() => {
				that.answertime++; //答题用时
				if (seconds <= 0) {
					if (times > 0) {
						that.seconds = seconds = 59;
						that.times = --times; //减分钟
					} else {
						//闯关结果
						that.passTheResults(1);
						//时间结束1
						clearInterval(that.timer)
					}
				} else {
					--seconds; //减秒数
					if (seconds <= 9) {
						that.seconds = '0' + seconds;
					} else {
						that.seconds = seconds;
					}
				}
			}, 1000);
		},
		//获取原始数据
		async getoriginalData() {
			var that = this;
			that.my_answer = [];
			if (that.type == 'sz') {
				that.originalData = that.number.slice(0, that.num * that.num);
				that.successnumberarr = that.number.slice(0, that.num * that.num);
			}
			if (that.type == 'zm') {
				that.originalData = that.letters.slice(0, that.num * that.num);
				that.successnumberarr = that.letters.slice(0, that.num * that.num);
			}
			if (that.type == '7jue') {
				that.originalData = await that.getMakeProjecTiku('7jue');
				that.successnumberarr = that.originalData['content'].split("");
			}
			if (that.type == '7lv') {
				that.originalData = await that.getMakeProjecTiku('7lv');
				that.successnumberarr = that.originalData['content'].split("");
			}
		},
		//得到项目题库
		getMakeProjecTiku(type = '') {
			var that = this;
			var data = {};
			data['project_id'] = 1;
			data['make_user_id'] = Cache.get('user_id');
			data['make_id'] = Cache.get('project_make_id');
			data['level'] = that.grade;
			data['type'] = type;
			return new Promise((resolve, reject) => {
				hitmatchcommon.getMakeProjecTikuLibMethod(data).then(res => {
					if (res) {
						resolve(res)
					}
				});
			})
		},
		//获取数组
		getnumber() {
			var that = this;
			var originalDataarr = that.originalData;
			var arr = [];
			if (that.type == '7lv' || that.type == '7jue') {
				var content = that.originalData['content']; //获取内容
				var originalDataarr = content.split(""); //分割字符串
			}
			for (var i = 0; i < (that.num * that.num); i++) {
				arr.push(originalDataarr[i]);
			}
			//保存出题
			that.numberarr = that.question = arr;

		},
		//打乱数组
		shuffle(arr) {
			var len = arr.length;
			for (var i = 0; i < len; i++) {
				var end = len - 1;
				var index = (Math.random() * (end + 1)) >> 0;
				var t = arr[end];
				arr[end] = arr[index];
				arr[index] = t;
			}
			return arr;
		},

		//点击事件1
		clicknumber(e) {
			var that = this;
			//判断是否显示开始，true=没有隐藏，不能点击。
			if (that.show) {
				return;
			}
			var nownumber = that.question[e]; //当前数字或者文字
			that.my_answer.push(nownumber); //推入我的答案
			that.clickEffects(e); //点击特效
			if (nownumber == that.successnumberarr[that.defaultdigit]) {
				that.defaultdigit = ++that.defaultdigit;
				console.log(that.defaultdigit);
			} else {
				clearInterval(that.timer)
				//闯关结果
				that.passTheResults(1);
			}
			if (that.defaultdigit == that.num * that.num) {

				clearInterval(that.timer)
				//闯关结果
				that.passTheResults();
			}
			// if (that.defaultdigit == e) {
			// 	that.defaultdigit = ++that.defaultdigit;
			// 	console.log(e)
			// }else {
			// 	console.log('错误');
			// }
		},
	}
}